require_dependency "search"
require "string_extensions.rb"
class Page < ActiveRecord::Base
  belongs_to                :user
  has_many                  :partnerships
  has_many                  :galleries, :through => :partnerships, :order => "created_at DESC"
  has_many                  :users,     :through => :partnerships, :order => "login"
  validates_presence_of     :user
  validates_presence_of     :title
  validates_presence_of     :content
  validates_presence_of     :description
  
  searches_on               :title,
                            :content,
                            :description
  
  after_save                :create_partnerships
  
  has_friendly_id           :title, :use_slug => true
  
  def private?
    !self.users.empty?
  end
  
  def text_only_content
    self.content.gsub(/<\/?[^>]*>/,  "")
  end
  
  def gallery_ids=(gallery_ids = [])
    @gallery_ids = gallery_ids
  end
  
  def user_ids=(user_ids = [])
    @user_ids = user_ids
  end
  
  def public?
    self.users.empty?
  end
  
  def is_private?
    !self.users.empty?
  end
  
  def is_invisible?
    self.invisible?
  end
  
protected
  def create_partnerships
    self.partnerships.each {|partnership| partnership.destroy if partnership.gallery and @gallery_ids or partnership.user and @user_ids} if self.partnerships
    @gallery_ids.each {|gallery_id| Partnership.create!(:page_id => self.id, :gallery_id => gallery_id)} unless @gallery_ids.nil?
    @user_ids.each {|user_id| Partnership.create!(:page_id => self.id, :user_id => user_id)} unless @user_ids.nil?
  end
end
